﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Spider.Common;
using Spider.Common.Http;
using Spider.DataAccess.Stock;
using Spider.Models.Stock;
using Spider.Common.Enums;

namespace Spider.Business.Stock
{
    public class StockCompanyBusiness : ISpider
    {
        StockCompanyDataAccess dataAccess = new StockCompanyDataAccess();

        public void SpiderData(object urlModel)
        {
            SourceUrlModel model = (SourceUrlModel)urlModel;
            var companyList = this.GetCompanyList(model.Url);
            dataAccess.AddCompanies(companyList);
        }

        public event UILogEventHandler SyncLog;
        private List<StockCompanyModel> GetCompanyList(string url)
        {
            HttpHelper helper = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = url,
                ContentType = "json"
            };
            int page = Convert.ToInt32(Utility.GetQueryStringValue(url, "page"));
            RankData rankData = new RankData();
            List<StockCompanyModel> companyList = new List<StockCompanyModel>();
            int prevPage = page;

            do
            {
                item.URL = item.URL.Replace("page=" + prevPage, "page=" + page);
                string jsonData = helper.GetHtml(item);
                string newString = jsonData.Substring(jsonData.IndexOf('=') + 1);
                rankData = JsonConvert.DeserializeObject<RankData>(newString);
                rankData.Rank.ForEach(e =>
                {
                    string[] dataArray = e.Split(',');
                    companyList.Add(new StockCompanyModel()
                    {
                        StockBourse = dataArray[0].EndsWith("1") ? BourseType.ShangHai : BourseType.ShenZhen,
                        StockCode = dataArray[1],
                        CompanyName = dataArray[2]
                    });
                });
                prevPage = page;
                page++;

            } while (rankData.Pages >= page);

            return companyList;
        }


        /// <summary>
        /// 同步UI 消息
        /// </summary>
        /// <param name="state"></param>
        /// <param name="message"></param>
        private void SyncUIMessage(ProcessState state, string message)
        {
            if (SyncLog != null)
            {
                SyncLog(state, message);
            }
        }


        public void SpiderAbort()
        {
            throw new NotImplementedException();
        }


        
    }

    public class RankData
    {
        public List<string> Rank { get; set; }
        public int Pages { get; set; }
    }
}
